﻿using AutoMapper;
using MediatR;
using SmartProduction.Domain.客户管理.WorkOrder;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Read.API.Application.Commands.Work_CaigouOrderCommand;

namespace SmartProduction.Read.API.Application.CommandHandlers.Work_CaigouOrderHandler
{
    /// <summary>
    /// 工单采购订单查询列表命令处理
    /// </summary>
    public class Work_CaigouOrderQueryCommandHandler : IRequestHandler<Work_CaigouOrderQueryCommand, APIResult<APIPaing<Work_CaigouOrder>>>
    {
        /// <summary>
        /// 采购订单仓储
        /// </summary>
        private readonly IBaseRepository<Work_CaigouOrder> caigouRepository;

        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="caigouRepository">采购订单仓储</param>
        /// <param name="mapper">映射</param>
        public Work_CaigouOrderQueryCommandHandler(IBaseRepository<Work_CaigouOrder> caigouRepository,IMapper mapper)
        {
            this.caigouRepository = caigouRepository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns></returns>
        public Task<APIResult<APIPaing<Work_CaigouOrder>>> Handle(Work_CaigouOrderQueryCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<APIPaing<Work_CaigouOrder>> result = new APIResult<APIPaing<Work_CaigouOrder>>();
                result.Code = APIEnums.查询成功;
                result.Msg = APIEnums.查询成功.ToString();
                var list = caigouRepository.GetAll().Result;
                if (!string.IsNullOrEmpty(request.OrderCode))
                {
                    list = list.Where(x => x.OrderCode == request.OrderCode);
                }
                if (!string.IsNullOrEmpty(request.OrderSubject))
                {
                    list = list.Where(x => x.OrderSubject == request.OrderSubject);
                }

                var count = list.Count();
                var page = (int)Math.Ceiling(count * 1.0 / request.PageSize);
                var models = list.OrderByDescending(x => x.Work__CaigouOrderId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
                APIPaing<Work_CaigouOrder> paging = new APIPaing<Work_CaigouOrder>();
                paging.PageCount = page;
                paging.TotalCount = count;
                paging.Items = mapper.Map<List<Work_CaigouOrder>>(models);
                result.data = paging;
                return Task.FromResult(result);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
